package xyz.zhouzhousag.server.common.aspect;
/**
 * Description:
 * <p>
 * ClassName: LogAspect
 * date: 2021/9/27 9:17
 *
 * @author Yin.Liu
 * @version 1.0
 * @since JDK 1.8
 */

import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.zhouzhousag.server.common.annotation.LogAnnotation;
import xyz.zhouzhousag.server.common.enums.LogStatusEnums;
import xyz.zhouzhousag.server.common.utils.HttpContextUtils;
import xyz.zhouzhousag.server.common.utils.HttpParamsUtils;
import xyz.zhouzhousag.server.common.utils.IpUtils;
import xyz.zhouzhousag.server.pojo.entity.AdminUser;
import xyz.zhouzhousag.server.pojo.entity.SysLog;
import xyz.zhouzhousag.server.service.AdminUserService;
import xyz.zhouzhousag.server.service.SysLogService;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @ClassName LogAspect
 * @Description 日志切面
 * @Author Yin.Liu8
 * @Date 2021/9/27 9:17
 * @Version 1.0
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private AdminUserService adminUserService;

    @Pointcut("@annotation(xyz.zhouzhousag.server.common.annotation.LogAnnotation)")
    public void logPointCut() {

    }


    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();

        //请求的参数
        String params = "";
        Object[] args = point.getArgs();
        try {
            params = HttpParamsUtils.argsArrayToString(args);
        } catch (Exception e) {

        }
        //执行方法
        Object returnResult = null;
        String result = "";
        int status;
        boolean isError = false;
        Exception exception = null;
        try {
            returnResult = point.proceed();
            if (returnResult == null) {
                result = "";
            } else {
                result = JSON.toJSONString(returnResult);
            }
            status = LogStatusEnums.NORMAL.getValue();
        } catch (Exception ex) {
            result = ex.getLocalizedMessage();
            status = LogStatusEnums.ERROR.getValue();
            exception = ex;
            isError = true;
        }

        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        savesweetOplog(point, time, params, result, status);

        if (isError) {
            throw exception;
        }

        return returnResult;
    }

    private void savesweetOplog(ProceedingJoinPoint joinPoint, long time, String params, String returnResult, Integer status) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        //请求的参数
        sysLog.setParams(params);

        // 返回参数
        sysLog.setResult(null);

        LogAnnotation syslog = method.getAnnotation(LogAnnotation.class);

        if (syslog != null) {
            //注解上的描述
            sysLog.setOperation(syslog.value());
            sysLog.setType(syslog.type().getValue());
            if (syslog.saveResult()) {
                sysLog.setResult(returnResult);
            }
        }


        //请求的状态
        sysLog.setStatus(String.valueOf(status));

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IpUtils.getIpAddr(request));

        //用户名
        String principal = (String) SecurityUtils.getSubject().getPrincipal();
        AdminUser adminUser = adminUserService.getByName(principal);
        sysLog.setUserId(adminUser.getAdminUserId());
        sysLog.setUsername(principal);

        sysLog.setTime(time);
        sysLog.setCreateDate(new Date());
        //保存系统日志
        sysLogService.insert(sysLog);
    }


}
